package com.example.test;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CommaStringDeserializer extends JsonDeserializer<List<String>> {
    @Override
    public List<String> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode node = mapper.readTree(jp);
        if (node.isArray()) {
            // Use the default deserialization for array nodes
            return mapper.readValue(node.traverse(), TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
        } else if (node.isTextual()) {
            // Use the custom deserialization for non-array nodes
            List<String> strList = new ArrayList<>(Arrays.asList(node.asText().split(",")));
            strList.removeIf(String::isEmpty);
            return strList;
        }
        return Collections.emptyList();
    }
}
